from Program.models import User, News, Category
from Program.utils.common import user_login_data
from Program.utils.response_code import RET
from Program import constants
from . import index_blu
from flask import render_template, current_app, jsonify, session, request, g


@index_blu.route('/')  # 装饰器传参：在创建函数的同时将url和函数名以字典形式存入url_map,参数methods不传默认为GET,必须为中括号形式
@user_login_data
def index():
    # ------------------------获取用户登陆信息---------------------------
    # 1.获取用户id
    # user_id = session.get("user_id")
    # user = None  # type:User    #解决本地本地变量无法在赋值前引用bug
    # # 2.查询用户数据
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)
    #         return jsonify(errno=RET.DBERR, ermsg="数据库查询错误")

    # 从装饰器中的g对象中获取当前登陆的用户
    user = g.user

    # 3.将数据转成字典包含字典的模型(利用对象已经封装好的to_dict方法)
    """
      基本格式：
      if user:
          user_info = user.to_dict()

      数据格式：
          "data": {
                  "user_info": {"id": self.id}
              }
      使用方式：data.user_info.id
      """
    # ------------------------获取点击排行---------------------------
    try:
        news_rank_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询新闻排行数据异常")
    """
    # news_rank_list 对象列表===》 [news1, news2, ...新闻对象 ]
    # news_rank_dict_list 字典列表===> [{新闻字典}, {}, {}]
    """
    # 字典列表初始化
    news_rank_dict_list = []
    # 将新闻对象列表转换成字典列表
    for news_obj in news_rank_list if news_rank_list else []:
        # 将新闻对象转成字典
        news_dict = news_obj.to_dict()
        # 构建字典列表
        news_rank_dict_list.append(news_dict)

    # ------------------------新闻分类展示---------------------------
    # 获取新闻分类数据
    categories = Category.query.all()
    # 定义列表保存分类数据
    categories_dicts = []

    for category in categories if categories else []:
        # 拼接内容
        categories_dicts.append(category.to_dict())
    print(categories_dicts)

    data = {
        "user_info": user.to_dict() if user else None,
        "news_rank_list": news_rank_dict_list,
        "categories": categories_dicts
    }

    return render_template('news/index.html', data=data)


@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')


# 新闻列表展示
@index_blu.route('/newslist')
def get_news_list():
    """
    获取指定分类的新闻列表
    1. 获取参数
    2. 校验参数
    3. 查询数据
    4. 返回数据
    :return:
    """
    # 1.获取参数
    args_dict = request.args
    page = args_dict.get("page", "1")  # 当前页码
    per_page = args_dict.get("per_page", constants.HOME_PAGE_MAX_NEWS)  # 每一页数据条数
    category_id = args_dict.get("cid", "1")  # 分类id

    # 2.校验参数
    if not category_id:
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")

    try:  # 将数据进行强制类型转换
        category_id = int(category_id)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 3.查询数据并分页
    filters = [News.status == 0]
    # 如果分类id不为0，那么添加分类id的过滤
    if category_id != 1:
        filters.append(News.category_id == category_id)
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
        # 获取查询出来的数据
        items = paginate.items
        # 获取到总页数
        total_page = paginate.pages
        current_page = paginate.page
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

    news_list = []
    for news in items if items else []:
        news_list.append(news.to_dict())

    # 4.返回数据
    return jsonify(errrno=RET.OK, errmsg="OK", totalPage=total_page, currentPage=current_page, newsList=news_list,
                   cid=category_id)
